const Koa = require("koa");
const app = new Koa();
const router = require("koa-router")();
const bodyParser = require("koa-bodyparser");

const query = require("./mysql");
//获取数据
router.get("/list",async ctx=>{
    const data = await query(`select * from aaa`);
    ctx.body={
        code:1,
        msg:"成功获取用户列表",
        data
    }
})


router.get("/user",async (ctx)=>{
    const {pagenum,pagesize} = ctx.query;
    if(pagenum&&pagesize){
        console.log(pagenum,pagesize)
        let select_sql="select * from aaa"
        let limit_sql = " limit ?,?"
        let stateIndex = (pagenum-1)*pagesize;
        const res = await query(select_sql+limit_sql,[
            stateIndex,Number(pagesize)
        ]);
        const total=await query("select count (*) as count from aaa");
        console.log(total[0].count)
        ctx.body={
            res,
            total:total[0].count
        }
    }
})

//添加用户
router.post('/post', async (ctx) => {
    //获取请求体参数
    const { name, mima } = ctx.request.body;
    //非空校验
    if (!name || !mima) {
        ctx.body = {
            code: 403,
            message: '参数不合法'
        }
    }
    let res = await query('insert into aaa (name,mima) values (?,?)', [name, mima]);
    //判断用户是否添加成功
    if (res.affectedRows !== 1) {
        ctx.body = {
            code: 403,
            message: '添加用户失败'
        }
    }
    ctx.body = {
        code: 200,
        message: '添加成功'
    }
})


//更新数据

router.put('/put',async ctx=>{
    const {name,mima,id}=ctx.request.body;
    const res=await query(`update aaa set name=?,mima=? where id=?`,[name,mima,id])
    ctx.body={
        code:1,
        msg:"更新成功"
    }
})

//删除数据
router.delete('/del',async ctx=>{
    const {id}=ctx.query;
    const res=await query(`delete from aaa where id=?`,[id])
    ctx.body={
        code:1,
        msg:"删除成功"
    }
})



app.use(bodyParser());
app.use(router.routes());

app.listen(9000,()=>{
    console.log("服务已启动，你可以访问：http://localhost:9000");
})